import { notification } from "ant-design-vue";
import { uuid } from "@/util/tools";

let ws: WebSocket;
let token: any;

const onOpen = () => {
  console.log("WebSocket连接成功,状态码:", ws.readyState);
};
const onMessage = (event: any) => {
  // console.log("WebSocket收到消息:", event.data);
  notification["info"]({
    message: "收到消息",
    description: event.data,
  });
};
const onError = () => {
  console.log("WebSocket连接错误,状态码:", ws.readyState);
};
const onClose = () => {
  console.log("WebSocket连接关闭,状态码:", ws.readyState);
};
const initWebSocket = () => {
  ws.addEventListener("open", onOpen); // 连接成功
  ws.addEventListener("message", onMessage); // 收到消息的回调
  ws.addEventListener("error", onError); // 连接错误
  ws.addEventListener("colose", onClose); // 连接关闭的回调
};

if ("WebSocket" in window) {
  token = uuid(10);
  // 连接地址:ws://127.0.0.1:8880/ws/xxx
  ws = new WebSocket(import.meta.env.VITE_SOCKET_URL + "/ws/" + token);
  initWebSocket();
} else {
  alert("当前浏览器 不支持");
}
